#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <opencv/cxcore.h>
#include <opencv/highgui.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include "cnats.h"
#include "clog.h"
#include "threads.h"

using namespace std;

class RecvHandler: public MsgHandler {
private:
    IplImage *img;
    int i;
public:
    RecvHandler():img(NULL){
	i = 0;
    }
    void execute(recvedMsgs *msg){
        //cvNamedWindow("w");
	clog::i("Recv : ");
	clog::il(i++);
        if(img != NULL){
            cvReleaseImage(&img);
        }
        CvMat m = cvMat(1, msg->dataLen, CV_8UC1, msg->data);
        img = cvDecodeImage(&m);
        if(img == NULL){
            printf("ERROR DECODE\n");
        }else{
            cvShowImage("tt",img);
            cvWaitKey(10);
        }
    }
};

int main(int argc, char const *argv[]){
    clog::setLevel(2);
    clog::il("Start");

    cnats* conn = cnats::Connect("nats://59.78.47.168:4222");
    conn->Subscribe(string("Img"), new RecvHandler() );
    while(1){
	cvWaitKey(10);
        // pFrame=cvQueryFrame( pCapture );
        // if(!pFrame){
        //     printf("Error Read Frame\n");
        //     continue;
        // }
        // cv::Mat img = cv::cvarrToMat(pFrame);
        // if (!cv::imencode(".jpg",img,buf) ){
        //     printf("Error Encode to jpg\n");
        // }else{
        //     printf("Code length %lu\n", buf.size());
        // }
        // if (!cv::imencode(".jpg",img,buf) ){
        //     printf("Error Encode to jpg\n");
        // }else{
        //     printf("Code length %lu\n", buf.size());
        // }        
    }
    return 0;
}
